package com.jamal2362.apktool.task;

import android.content.Context;
import java.io.File;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParserException;
import com.jamal2362.apktool.R;
import com.jamal2362.apktool.fragment.files.Refreshable;
import com.jamal2362.apktool.util.FileUtils;
import com.jamal2362.apktool.util.Manifest;
import com.jamal2362.apktool.util.Settings;

public class SignTask extends AbstractTask
{
	private final SignUtil signTool;
	private Context context;
	
	public SignTask(Context ctx, Refreshable refresh, SignUtil signTool)
	{
		super(ctx, refresh);
		this.context = ctx;
		this.signTool = signTool;
	}

	@Override
	protected int getTitle()
	{
		return R.string.sign_run_title;
	}

	@Override
	protected boolean process(File f)
	{
		info(R.string.sign_run_title, (Object) null);
		int minSdk = 14;
		try
		{
			Manifest mf = new Manifest(f);
			minSdk = mf.getMinSdkVersion();
		}
		catch (XmlPullParserException e)
		{}
		catch (IOException e)
		{}
		if (minSdk < 1)
			minSdk = 14;
		File out = getOutFile(f, f.getName(), this);
		return signTool.sign(f, out, minSdk, this);
	}
	
	public File getOutFile(File f, String name, AbstractTask task)
	{
		String dir = f.getParent();
		if (name == null)
			name = f.getName();
		boolean allToOut = Settings.getb(context, "all_to_out_dir", false);
		boolean noaccess = !f.getParentFile().canWrite();
		if (allToOut || noaccess)
		{
			dir = Settings.output_directory;
			if (dir == null)
			{
				task.warning(R.string.output_directory_not_set);
				return null;
			}
			File d =  new File(dir);
			if (!d.exists() && !d.mkdirs())
			{
				task.warning(R.string.output_directory_not_extsts, dir);
				return null;
			}
			if (!d.isDirectory())
			{
				task.warning(R.string.not_directory, dir);
				return null;
			}
		}
		setResult(dir);
		name = FileUtils.genNameApk(context, dir, name, "_sign", 0);
		return new File(dir, name);
	}
}
